
import ContentLayout from '@/layouts/ContentLayout'
import ArrayUtils from '@/utils/ArrayUtils'
import { PROJECT_QA_STATUS } from '@/consts/project'
import { Button, Table, Tag } from 'antd'
import { useState, useEffect } from 'react'
import styles from './style.less'
import { history } from 'umi';
import UserBrief from '@/components/UserBrief'
import { formetDate, formetTime_MDHm } from '@/utils/dateUtils'
import ProjectProdSelect from '@/pages/projects/components/ProjectProduct/ProjectProdSelect'
import ProjectDevSelect from '@/pages/projects/components/ProjectDev/ProjectDevSelect'
import CheckActon from '../../CheckActoin'
import ActionDropdown from '@/components/ActionDropdown';
import { pageQA } from '@/services/project/qa'
import QaAddModal from './../QaAddModal'


export const QAStatus = (props) => {
    const {
        status,
    } = props

    if (status || status === 0) {
        return <Tag color={PROJECT_QA_STATUS[status]?.color}>{PROJECT_QA_STATUS[status]?.name}</Tag>
    }
    return (
        <Tag>/</Tag>
    )
}


const QaPage = (props) => {
    const {
        projectId,
        showProdColumn = true,
        onQueryParamChange,
        queryInitParams = {},
        projectPermission
    } = props

    const [params, setParams] = useState({
        pageNum: 1,
        pageSize: 10
    })
    const [showAddQAModalVisiable, setShowAddQAModalVisiable] = useState(false)
    const [qaPage, setQaPage] = useState()
    const [qaPageLoading, setQaPageLoading] = useState()
    const [permission, setPermission] = useState({})

    useEffect(() => {
        let initParam = {
            ...params,
            ...queryInitParams
        }
        setParams(initParam)
        if (projectId) {
            queryQAPage(initParam)
        }
    }, [projectId])

    useEffect(() => {
        setPermission({
            ...projectPermission?.qa
        })
    }, [projectPermission])

    const onParamChange = (param, doQuery) => {
        if (param && !param.pageNum) {
            param.pageNum = 1;
        }
        let newParams = { ...params, ...param }
        setParams(newParams)
        if (onQueryParamChange) {
            onQueryParamChange(newParams)
        }
        if (doQuery) {
            queryQAPage(newParams)
        }
    }

    const queryQAPage = (queryParams) => {
        setQaPageLoading(true)
        pageQA(projectId, (queryParams || params))
            .then(({ data }) => {
                setQaPageLoading(false)
                setQaPage(data)
            })
    }

    const showQADetail = (prod) => {
        history.push(`/projects/${projectId}/qa/${prod.id}`)
    }


    const queryItems = [
        {
            name: "inStatus",
            label: "状态",
            isMain: true,
            span: 24,
            type: "tagSelect",
            options: ArrayUtils.jsonToArray(PROJECT_QA_STATUS).map((item) => ({
                value: item.key,
                label: item.value.name
            }))
        },
        {
            name: "likeName",
            label: "名称",
            isMain: true,
            span: 8,
            type: "input",
        },
        {
            name: "inUserId",
            label: "负责人",
            isMain: true,
            span: 8,
            type: "userSelect",
        }, {
            name: "inProjectProdItemId",
            label: "迭代",
            isMain: true,
            span: 8,
            type: "custom",
            render: () => {
                return <ProjectProdSelect
                    allowClear={true}
                    ismultiple={true}
                    onChange={(value) => {
                        onParamChange({
                            inProjectProdItemId: value
                        }, true)
                    }}
                    projectId={projectId} />
            }
        }, {
            name: "inProjectDevItemId",
            label: "迭代",
            isMain: true,
            span: 8,
            type: "custom",
            render: () => {
                return <ProjectDevSelect
                    allowClear={true}
                    ismultiple={true}
                    onChange={(value) => {
                        onParamChange({
                            inProjectDevItemId: value
                        }, true)
                    }}
                    projectId={projectId} />
            }
        }


    ]
    const saveQA = () => {
        queryQAPage();
        setShowAddQAModalVisiable(false);
    }


    const actionHeader = [
        <ActionDropdown
            key="actions"
            status={params?.isArchived && "filter"}
            placement="bottomRight"
            actions={[
                <CheckActon
                    check={params?.isArchived === 1}
                    onChange={(value) => {
                        if (value) {
                            onParamChange({
                                isArchived: 1
                            }, true)
                        } else {
                            onParamChange({
                                isArchived: null
                            }, true)
                        }
                    }}
                    label={'查看归档数据'}
                />,
            ]}
        />,
        <Button type="primary" size="middle" onClick={() => {
            setShowAddQAModalVisiable(true)
        }}>
            新增
        </Button>,
        ,
        <CheckActon
            check={params?.mySelection === 1}
            onChange={(value) => {
                if (value) {
                    onParamChange({
                        mySelection: 1
                    }, true)
                } else {
                    onParamChange({
                        mySelection: null
                    }, true)
                }
            }}
            label={'只看我的'}
        />
    ]

    const tableColumns = [
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            width: "20%",
            fixed: 'left',
            ellipsis: {
                showTitle: true
            },
            sorter: (a, b) => a.name.localeCompare(b.name),
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width: "10%",
            sorter: (a, b) => a.status - b.status,
            render: (text, record) => <QAStatus status={record.status}></QAStatus>
        },
        {
            title: '所属迭代',
            dataIndex: 'projectProdItemId',
            key: 'projectProdItemId',
            ellipsis: {
                showTitle: true
            },
            render: (text, record) => record.projectProdItem?.name
        },
        {
            title: '所属开发项',
            dataIndex: 'projectDevItemId',
            ellipsis: {
                showTitle: true
            },
            key: 'projectDevItemId',
            render: (text, record) => record.projectDevItem?.name

        },
        {
            title: '负责人',
            dataIndex: 'userId',
            ellipsis: true,
            key: 'userId',
            width: "14%",
            render: (text, record) => <UserBrief user={record.user}></UserBrief>,
        },
        {
            title: '排期',
            dataIndex: 'date',
            key: 'date',
            width: "200px",
            ellipsis: {
                showTitle: true
            },
            render: (text, record) => record.actualStartDate ? (`${formetDate(record.actualStartDate)}~${formetDate(record.actualEndDate)}`)
                : (`${formetDate(record.planStartDate)}~${formetDate(record.planStartDate)}`),
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            width: "18%",
            sorter: (a, b) => a.createTime.localeCompare(b.createTime),
            render: (text, record) => formetTime_MDHm(record.createTime),
            defaultSortOrder: 'descend'
        }
    ]

    const filterColumn = (tableColumns) => {
        let showColumns
        if (!showProdColumn) {
            showColumns = tableColumns.filter(column => column.key !== 'projectProdItemId')
        } else {
            showColumns = tableColumns;
        }
        // if (tableColumns) {
        //     return tableColumns.filter(column => column.key === 'name'
        //         || column.key === 'status'
        //     )
        // }
        return showColumns;
    }


    return <>
        <ContentLayout
            queryItems={queryItems}
            actionHeader={actionHeader}
            queryInitParams={queryInitParams}
            onQueryChange={onParamChange}
            content={
                <Table
                    onChange={(pagination, filters, sorter) => {
                        console.log(pagination, sorter)
                        onParamChange({
                            pageNum: pagination.pageSize === params.pageSize ? pagination.current : 1,
                            pageSize: pagination.pageSize
                        }, true)
                    }}
                    columns={filterColumn(tableColumns)}
                    rowKey="id"
                    loading={qaPageLoading}
                    dataSource={qaPage && qaPage.list}
                    pagination={{
                        position: ["bottomCenter"],
                        showSizeChanger: true,
                        pageSize: params.pageSize || 10,
                        total: qaPage && qaPage.count,
                        current: qaPage && qaPage.pageNum,
                        pageSizeOptions: [10, 20, 50],
                        showTotal: (total, range) => `总数： ${total} `
                    }}
                    size="small"
                    onRow={record => {
                        return {
                            onClick: () => {
                                showQADetail(record)
                            }
                        }
                    }}
                >
                </Table>
            }
        />
        <QaAddModal
            projectId={projectId}
            visible={showAddQAModalVisiable}
            onCancel={() => {
                setShowAddQAModalVisiable(false)
            }}
            onSaveSuccess={saveQA} />
    </>
}


export default QaPage;